/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.agera.database;

import static com.google.agera.Result.absentIfNull;
import static com.google.agera.Result.failure;

import com.google.agera.NonNull;
import com.google.agera.Result;
import com.google.agera.Supplier;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSetHook;

/**
 * Abstract extension of {@link DatabaseHelper} implementing a sql database {@link Supplier} to be
 * used with the {@link SqlDatabaseFunctions}.
 */
public abstract class SqlDatabaseSupplier extends DatabaseHelper implements Supplier<Result<RdbStore>> {
    public SqlDatabaseSupplier(@NonNull final Context context) {
        super(context);
    }

    protected abstract StoreConfig getStoreConfig();

    protected abstract int getVersion();

    protected abstract RdbOpenCallback getRdbOpenCallback();

    protected abstract ResultSetHook getResultSetHook();

    @NonNull
    @Override
    public final synchronized Result<RdbStore> get() {
        try {
            return absentIfNull(getRdbStore(getStoreConfig(), getVersion(), getRdbOpenCallback(), getResultSetHook()));
        } catch (final Exception e) {
            return failure(e);
        }
    }
}
